package com.archstoday.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.archstoday.BaseApp;
import com.archstoday.R;
import com.archstoday.activity.LoginActivity;
import com.archstoday.activity.SchemeDetailActivity;
import com.archstoday.adapter.MainSchemeAdapter;
import com.archstoday.common.AsRes;
import com.archstoday.common.SpfUtils;
import com.archstoday.entity.BaseEntity;
import com.archstoday.entity.SchemeListEntity;
import com.archstoday.event.MessageRefreshSchemeEvent;
import com.archstoday.utils.OAuthUtils;
import com.archstoday.utils.ToolUtils;
import com.archstoday.view.PullToRefreshLayout;
import com.base.http.common.BaseHttpClient;
import com.base.utils.MySharedPreferencesMgr;
import com.base.utils.StringUtil;
import com.xw.repo.refresh.PullListView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 方案列表页
 */
public class MainSchemeFragment extends AsBaseFragment implements PullToRefreshLayout.OnRefreshListener {

    private RelativeLayout mTipLayout;
    private TextView mAllTv, mNewTv, mScreenBtn;
    private PullToRefreshLayout mPullLayout;
    private PullListView mPullList;
    private ProgressBar mProgress;
    private LinearLayout mNoneLayout;

    private View mFootView;
    private String mSlipType;
    private MainSchemeAdapter mAdapter;
    private boolean isFirst;
    private String mSince, mMax;

    private MyTimeTask mTimeTask;
    private Timer timer;
    private int recLen;
    private boolean isLoadMore;

    private int mIndex;

    @Override
    protected View initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_list, null);
        mTipLayout = (RelativeLayout) view.findViewById(R.id.fragment_tip_layout);
        mAllTv = (TextView) view.findViewById(R.id.main_all_tv);
        mNewTv = (TextView) view.findViewById(R.id.main_new_tv);
        mScreenBtn = (TextView) view.findViewById(R.id.main_screen_btn);
        mPullLayout = (PullToRefreshLayout) view.findViewById(R.id.pull_layout);
        mPullList = (PullListView) view.findViewById(R.id.pull_list);
        mPullLayout.setOnRefreshListener(this);
        mProgress = (ProgressBar) view.findViewById(R.id.progress_bar);
        mNoneLayout = (LinearLayout) view.findViewById(R.id.search_none_layout);

        return view;
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        EventBus.getDefault().register(this);

        mFootView = LayoutInflater.from(mAct).inflate(R.layout.view_load_more, null);
        mTipLayout.setVisibility(View.GONE);
        mAllTv.setVisibility(View.GONE);
        mScreenBtn.setVisibility(View.GONE);
        mNewTv.setVisibility(View.GONE);
        mSlipType = AsRes.REFRESH;

        mSince = ToolUtils.getSince();
        mMax = ToolUtils.getSince();
        mAdapter = new MainSchemeAdapter(mAct, click);
        mPullList.setAdapter(mAdapter);
        isFirst = true;
        isLoadMore = false;
        upData();
    }

    @Override
    protected void initListener() {
        mPullList.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (mAdapter.getItem(i) != null) {
                    Map<String, String> info = new HashMap<>();
                    info.put("articleId", String.valueOf(mAdapter.getItem(i).getId()));
//                    info.put("categoryId1", String.valueOf(mAdapter.getItem(i).))
                    getEvent(BaseApp.E_DETAILS, BaseApp.PAGE_TYPE_SCHEME,
                            ToolUtils.mapToJson(info));

                    Intent intent = new Intent(mAct, SchemeDetailActivity.class);
                    intent.putExtra("id", mAdapter.getItem(i).getId());
                    startActivity(intent);
                }
            }
        });
    }

    @Override
    public void treatClickEvent(View view) {
        switch (view.getId()) {
            case R.id.id_for_focus:
                if (StringUtil.isEmpty(MySharedPreferencesMgr.getString(SpfUtils.USER_ID, ""))) {
                    showToast(R.string.user_userid_null);

                    Intent loginIntent = new Intent(getActivity(), LoginActivity.class);
                    startActivity(loginIntent);
                    return;
                }
                getEvent(BaseApp.E_ATTENTION_CLK, BaseApp.PAGE_TYPE_ATTENTION_CLK);

                mIndex = (int) view.getTag();

                SchemeListEntity.DataModel dataBean = mAdapter.getItem(mIndex);
                if (dataBean.getIsArticleUserLiked() == 1) {//已经关注，修改为未关注
                    processUserInfo(dataBean, 0);
                    focus(mAdapter.getItem(mIndex), "del");
                } else {
                    processUserInfo(dataBean, 1);
                    focus(mAdapter.getItem(mIndex), "add");
                }

                mAdapter.notifyDataSetChanged();
                break;
        }
    }

    private void processUserInfo(SchemeListEntity.DataModel dataBean, int flag) {
        int focusId = dataBean.getUserId();
        for (int i = 0; i < mAdapter.getData().size(); i++) {
            SchemeListEntity.DataModel currentData = mAdapter.getData().get(i);

            if (focusId == currentData.getUserId()) {
                currentData.setIsArticleUserLiked(flag);
            }
        }
    }

    private void focus(SchemeListEntity.DataModel dataBean, String action) {
        initParameter();
        mParams.put("userIdLiked", dataBean.getUserId());
        mParams.put("userId", MySharedPreferencesMgr.getString(SpfUtils.USER_ID, ""));
        mParams.put("token", MySharedPreferencesMgr.getString(SpfUtils.USER_TOKEN, ""));
        mParams.put("plat", "android");
        mParams.put("ifa", BaseApp.getDeviceID(getActivity()));
        mParams.put("action", action);

        sendEncryptPostRequest(AsRes.getInstance().getUrl(AsRes.FOCUS_AUTHOR),
                AsRes.FOCUS_AUTHOR, mParams, BaseEntity.class);
    }

    private void upData() {
        if (mAdapter.getCount() > 0) {
            mMax = mAdapter.getItem(0).getUpdateTime();
            mSince = mAdapter.getItem(mAdapter.getCount() - 1).getUpdateTime();
        }

        initParameter();
        mParams.put("pageSize", 20);
        mParams.put("slipType", mSlipType);
        mParams.put("since", mSince);
        mParams.put("max", mMax);
        mParams.put("range", 60);
        mParams.put("userId", MySharedPreferencesMgr.getString(SpfUtils.USER_ID, ""));
        mParams.put("token", MySharedPreferencesMgr.getString(SpfUtils.USER_TOKEN, ""));

        sendEncryptPostRequest(AsRes.getInstance().getUrl(AsRes.GET_SCHEME_LIST),
                AsRes.GET_SCHEME_LIST, mParams, SchemeListEntity.class);
    }

    @Override
    protected void onSuccess(String content, BaseHttpClient client, Object parse) {
        mProgress.setVisibility(View.GONE);
        mPullLayout.refreshFinish(true);
        mPullLayout.loadMoreFinish(true);
        if (client.getUrlIdentifier() == AsRes.GET_SCHEME_LIST) {
            SchemeListEntity entity = (SchemeListEntity) parse;
            if (ToolUtils.isSuccess(entity.getStatus())) {
                if (entity.getData() != null && entity.getData().size() > 0) {
                    mNoneLayout.setVisibility(View.GONE);
                    if (mSlipType == AsRes.REFRESH) {
                        mAdapter.setData(entity.getData());
                    } else {
                        mAdapter.addData(entity.getData());
                    }
                } else {
                    if (mSlipType == AsRes.REFRESH) {
                        if (isFirst) {
                            mSlipType = AsRes.LOADMORE;
                            upData();
                        } else {
                            if (mAdapter.getCount() == 0) {
                                mNoneLayout.setVisibility(View.VISIBLE);
                                mPullList.setPullUpEnable(false);
                            }
                        }
                    } else {
                        if (isLoadMore) {
                            mNoneLayout.setVisibility(View.GONE);
                            mPullList.addFooterView(mFootView);
                            mPullList.setPullUpEnable(false);
                        } else {
                            mNoneLayout.setVisibility(View.VISIBLE);
                            mPullList.setPullUpEnable(false);
                        }
                    }
                }
                if (isFirst) {
                    isFirst = !isFirst;
                } else {
                    if (mSlipType == AsRes.REFRESH) {
                        if (mTimeTask != null) {
                            mTimeTask.cancel();
                        }
                        timer = new Timer();
                        mTimeTask = new MyTimeTask();
                        recLen = 2;
                        timer.schedule(mTimeTask, 1000, 1000);
                        if (entity.getSize() > 0) {
                            mTipLayout.setVisibility(View.VISIBLE);
                            mNewTv.setVisibility(View.VISIBLE);
                            mNewTv.setText(entity.getSize() + mAct.getString(R.string.main_tip_new));
                        } else {
                            mTipLayout.setVisibility(View.VISIBLE);
                            mNewTv.setVisibility(View.VISIBLE);
                            mNewTv.setText(mAct.getString(R.string.main_tip_new_null));
                        }
                    }
                }
            } else {
                showToast(entity.getMsg());
            }
        } else if (client.getUrlIdentifier() == AsRes.FOCUS_AUTHOR) {
            BaseEntity entity = (BaseEntity) parse;
            if (ToolUtils.isSuccess(entity.getStatus())) {
                
            } else if (entity.getStatus() == 10005) {
                MySharedPreferencesMgr.setString(SpfUtils.USER_ID, "");
                MySharedPreferencesMgr.setString(SpfUtils.USER_TOKEN, "");
                OAuthUtils.getInstance().cleanUserInfo();

                showToast("登录信息已过期，请重新登录");
                Intent intent = new Intent(mAct, LoginActivity.class);
                startActivity(intent);
            } else {
                showToast(entity.getMsg());
            }
        }
    }

    @Override
    protected void onError(Throwable error, BaseHttpClient client) {
        new Thread() {
            @Override
            public void run() {
                new Handler(Looper.getMainLooper()).post(runnable);
            }
        }.start();
    }

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            mProgress.setVisibility(View.GONE);
            mPullLayout.refreshFinish(true);
            mPullLayout.loadMoreFinish(true);

            if (mAdapter.getCount() == 0) {
                mNoneLayout.setVisibility(View.VISIBLE);
                mPullList.setPullUpEnable(false);
            }

            showToast(R.string.intent_error);
        }
    };

    @Override
    public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
        mPullList.setPullUpEnable(true);
        mPullList.removeFooterView(mFootView);
        mSlipType = AsRes.REFRESH;
        upData();
    }

    @Override
    public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
        isLoadMore = true;
        mTipLayout.setVisibility(View.GONE);
        mSlipType = AsRes.LOADMORE;
        upData();
    }

    class MyTimeTask extends TimerTask {
        @Override
        public void run() {
            recLen--;
            Message message = new Message();
            handler.sendMessage(message);
        }
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (recLen < 0) {
                if (mTimeTask != null) {
                    mTimeTask.cancel();
                }
                timer.cancel();
                mTipLayout.setVisibility(View.GONE);
            }
        }
    };

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageRefreshSchemeEvent event) {
        isFirst = true;
        isLoadMore = false;
        upData();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}